package Receivers

import "gitee.com/ling-bin/network/netInterface"

//SpliceStartAndLengthReceiver 开始加长度分包
type SpliceStartAndLengthReceiver struct {
	symbol byte
	length int
}

//NewSpliceStartAndLengthReceiver 开始加长度分包
func NewSpliceStartAndLengthReceiver(symbol byte,length int) *SpliceStartAndLengthReceiver  {
	return &SpliceStartAndLengthReceiver{
		symbol: symbol,
		length: length,
	}
}

//GetHeadLen 包头必须要的长度
func (s *SpliceStartAndLengthReceiver) GetHeadLen() int {
	return 2
}

//CanHandle 是否能处理
func (s *SpliceStartAndLengthReceiver) CanHandle(conn netInterface.IConnection, buffer []byte) bool {
	return buffer[0] == s.symbol
}

//Reset 重置分包状态为初始状态
func (s *SpliceStartAndLengthReceiver) Reset()  {

}

//Receiver 分包处理
func (s *SpliceStartAndLengthReceiver) Receiver(conn netInterface.IConnection, buffer []byte) ([]byte, int) {
	var (
		bfLen         = len(buffer)
		startIndex    = -1
		currentLength = 0
		isStart       = false
	)
	for i := 0; i < bfLen; i++ {
		if !isStart {
			if buffer[i] == s.symbol {
				isStart = true
				startIndex = i
				currentLength = 1
			}
			continue
		}
		currentLength++
		if currentLength == s.length {
			hData := buffer[startIndex : i+1]
			startIndex = i + 1
			return hData, i + 1
		}
	}
	return nil, startIndex
}